<?php

namespace App\Models;

use App\Models\Comment;
use App\Repositories\CommentRepository;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
use ScoutElastic\Searchable;
use App\IndexConfigurators\CommentDetailIndexConfigurator;
use App\SearchRules\CommentDetailSearchRule;

class CommentDetail extends Model
{
    use SoftDeletes;
//    use Searchable;

    protected $fillable = ['cid', 'content'];
    
    protected $touches = ['comment'];//联动更新comment()方法中模型

    const CONTENT_TYPE_TEXT = 'text';
    const CONTENT_TYPE_IMAGE = 'image';

    protected $indexConfigurator = CommentDetailIndexConfigurator::class;

    protected $searchRules = [
        CommentDetailSearchRule::class
    ];

    public static function booted()
    {

    }

    public function getExcerptAttribute()
    {
        return CommentRepository::getDetailExcerpt($this->content);
    }

    public function getContentAttribute($value)
    {
        $contentArr = json_decode($value, true);

        return $contentArr;
    }

    public function setContentAttribute($value)
    {
        if (is_array($value)) {
            $this->attributes['content'] = json_encode_unicode($value);
        }
    }


    
    public function comment()
    {
        return $this->belongsTo(Comment::class, 'cid', 'id');
    }

    public function attachments()
    {
        return $this->morphToMany(
            Attachment::class,
            "target",
            AttachmentRelationship::TABLE_NAME,
            "target_id",
            "attachment_id",
            "cid",
            "id"
        );
    }

}
